package com.aqumon.www.controller;


import com.aqumon.www.constants.enums.StatusCode;
import com.aqumon.www.entity.exception.CaseServerException;
import com.aqumon.www.entity.persistent.RaaSTestAcc;
import com.aqumon.www.entity.request.cases.CaseDeleteReq;
import com.aqumon.www.entity.request.data.*;
import com.aqumon.www.entity.response.controller.Response;
import com.aqumon.www.service.RaaSTestAccService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * raas 测试账号 前端控制器
 * </p>
 *
 * @author aqumon
 * @since 2022-06-02
 */
@RestController
@RequestMapping("/api/RaaS")
public class RaaSTestAccController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RaaSTestAccController.class);

    @Resource
    RaaSTestAccService raaSTestAccService;

    /**
     * 导入账号
     * @param file
     * @param request
     * @return
     */
    @PostMapping(value = "/importAccount", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Response<?> importAccountExcel(@RequestParam MultipartFile file, String creator, HttpServletRequest request) {
        RaaSAccountImportReq req = new RaaSAccountImportReq(file, creator);
        req.validate();
        try {
            List<RaaSTestAcc> raaSTestAccList = raaSTestAccService.importAccountExcel(req, request);
            return Response.success(raaSTestAccService.saveBatch(raaSTestAccList, 1000));
        } catch (CaseServerException e) {
            throw new CaseServerException(e.getLocalizedMessage(), e.getStatus());
        } catch (Exception e) {
            LOGGER.error("[导入x-excel出错] 传参req={},错误原因={}", req.toString(), e.getMessage());
            e.printStackTrace();
            return Response.build(StatusCode.FILE_IMPORT_ERROR.getStatus(), StatusCode.FILE_IMPORT_ERROR.getMsg());
        }
    }

    /**
     * 导入账号（easyexcel demo）
     * @param file
     * @param request
     * @return
     */
    @PostMapping(value = "/importAcc", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Response<?> importAcc(@RequestParam MultipartFile file, String creator, HttpServletRequest request) {
        RaaSAccountImportReq req = new RaaSAccountImportReq(file, creator);
        req.validate();
        try {
            List<RaaSTestAcc> raaSTestAccList = raaSTestAccService.importAccExcel(req, request);
            return Response.success(raaSTestAccService.saveBatch(raaSTestAccList, 1000));
        } catch (CaseServerException e) {
            throw new CaseServerException(e.getLocalizedMessage(), e.getStatus());
        } catch (Exception e) {
            LOGGER.error("[导入x-excel出错] 传参req={},错误原因={}", req.toString(), e.getMessage());
            e.printStackTrace();
            return Response.build(StatusCode.FILE_IMPORT_ERROR.getStatus(), StatusCode.FILE_IMPORT_ERROR.getMsg());
        }
    }

    /**
     * @param ids (可选参数, 指存储账号的id序号)
     * 导出账号（easyexcel 导出）
     * @return 无返回值
     */
    @GetMapping(value = "/exportAcc")
    public void exportAcc(@RequestParam ArrayList<String> ids, HttpServletResponse response) {
        try {
            raaSTestAccService.exportAccExcel(ids, response);
        } catch (CaseServerException e) {
            throw new CaseServerException(e.getLocalizedMessage(), e.getStatus());
        } catch (Exception e) {
            LOGGER.error("[导出x-excel出错] 响应={},错误原因={}", response.toString(), e.getMessage());
            e.printStackTrace();
            response.setStatus(StatusCode.FILE_EXPORT_ERROR.getStatus());
        }
    }

    /**
     * 查询账号
     * @param flagUsage
     * @param project
     * @param holdings
     * @param pageNum
     * @param pageSize
     * @return 账号列表
     */
    @GetMapping(value = "/listAcc")
    public Response<?> listAccount(@RequestParam(required = false)  String flagUsage,
                                   @RequestParam(required = false)  String project,
                                   @RequestParam(required = false)  String holdings,
                                   @RequestParam(defaultValue = "1") Integer pageNum,
                                   @RequestParam(defaultValue = "10") Integer pageSize) {
        RaaSAccQueryReq raaSAccQueryReq = new RaaSAccQueryReq(flagUsage, project, holdings, pageNum, pageSize);
        try {
            return Response.success(raaSTestAccService.getRaaSAccList(raaSAccQueryReq));
        } catch (CaseServerException e) {
            throw new CaseServerException(e.getLocalizedMessage(), e.getStatus());
        } catch (Exception e) {
            LOGGER.error("[查询出错] 传参req={},错误原因={}", raaSAccQueryReq, e.getMessage());
            e.printStackTrace();
            return Response.build(StatusCode.INTERNAL_ERROR.getStatus(), StatusCode.INTERNAL_ERROR.getMsg());
        }
    }

    /**
     * 添加账号
     * @param raaSAccAddReq
     * @return
     */
    @PostMapping(value = "/addAcc")
    public Response<?> addAccount(@RequestBody(required = false) RaaSAccAddReq raaSAccAddReq){
        try {
            return Response.success(raaSTestAccService.saveAccount(raaSAccAddReq));
        } catch (CaseServerException e) {
            throw new CaseServerException(e.getLocalizedMessage(), e.getStatus());
        } catch (Exception e) {
            LOGGER.error("[查询出错] 传参req={},错误原因={}", raaSAccAddReq, e.getMessage());
            e.printStackTrace();
            return Response.build(StatusCode.INTERNAL_ERROR.getStatus(), StatusCode.INTERNAL_ERROR.getMsg());
        }
    }

    /**
     * 编辑账号
     * @param raaSAccEditReq
     * @return
     */
    @PostMapping(value = "/editAcc")
    public Response<?> editAccount(@RequestBody(required = false) RaaSAccEditReq raaSAccEditReq){
        try {
            return Response.success(raaSTestAccService.editAccount(raaSAccEditReq));
        } catch (CaseServerException e) {
            throw new CaseServerException(e.getLocalizedMessage(), e.getStatus());
        } catch (Exception e) {
            LOGGER.error("[查询出错] 传参req={},错误原因={}", raaSAccEditReq, e.getMessage());
            e.printStackTrace();
            return Response.build(StatusCode.INTERNAL_ERROR.getStatus(), StatusCode.INTERNAL_ERROR.getMsg());
        }
    }

    /**
     * 删除测试账号
     * @param request 请求体
     * @return 响应体
     */
    @PostMapping(value = "/delAcc")
    public Response<?> delAcc(@RequestBody RaaSDelReq request) {
        request.validate();
        try {
            return Response.success(raaSTestAccService.delAcc(request.getId()));
        } catch (CaseServerException e) {
            throw new CaseServerException(e.getLocalizedMessage(), e.getStatus());
        } catch (Exception e) {
            LOGGER.error("[RaaS Acc Delete]Delete RaaS Acc failed. params={} e={} ", request.toString(), e.getMessage());
            e.printStackTrace();
            return Response.build(StatusCode.SERVER_BUSY_ERROR);
        }
    }
}
